package com.rrx.mapper;

import com.rrx.model.Role;
import org.apache.ibatis.annotations.*;

@Mapper
public interface RoleMapper {
    @Insert("insert into role (name, remark) values(#{name}, #{remark})")
    public int addRole(@Param("name") String name, @Param("remark") String remark);

    @Insert("insert into menu_and_role (menuid, roleid) values(#{menuId}, #{roleId})")
    public int addRoleAndMenu(@Param("menuId") int menuId, @Param("roleId") int roleId);

    @Select("select id from role where name=#{name}")
    public Integer getIdByName(@Param("name") String name);

    @Insert("insert into role_and_permission (roleid, permission) values(#{roleid}, #{permission})")
    public int addRoleAndPermission(@Param("roleid") int roleId, @Param("permission") String permission);

    @Select("select roleid from admin_and_role where adminid = #{id}")
    public int[] getRolesById(@Param("id") int id);

    @Select("select permission from role_and_permission where roleid = #{id}")
    public String[] getPermissionsById(@Param("id") int id);

    @Select("select id from menu where menu_permission = #{permission}")
    public Integer getMenuByPermission(@Param("permission") String permission);

    /**
     * 通过管理员ID获取所有角色名
     * @param id  管理员ID
     * @return
     */
    @Select("select r.name from role r,admin_and_role aar where aar.adminid = #{id} and r.id = aar.roleid")
    public String[] getPermissionByAdmin(@Param("id") int id);

    @Select("select id,name,remark from role")
    public Role[] getRoleList();

    @Insert("insert into admin_and_role (adminid, roleid) values(#{adminId}, #{roleId})")
    public int addRoleToAdmin(@Param("adminId") int adminId, @Param("roleId") int roleId);

    /**
     * 通过管理员ID获取管理员所有角色
     * @param id  管理员ID
     * @return
     */
    @Select("select r.id as id, r.name as name from role r, admin_and_role aar where r.id = aar.roleid and aar.adminid = #{adminId}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "name", property = "name")
    })
    public Role[] getAdminRoles(@Param("adminId") int id);

    /**
     * 修改角色信息
     * @param name     角色名
     * @param remark   角色备注
     * @param id       角色ID
     * @return
     */
    @Update("update role set name = #{name}, remark = #{remark} where id = #{id}")
    public int updateRole(@Param("name") String name, @Param("remark") String remark, @Param("id") int id);

    /**
     * 删除所有权限
     * @param id
     * @return
     */
    @Delete("delete from role_and_permission where roleid = #{id}")
    public int deleteAllPermission(@Param("id") int id);

    /**
     * 添加一个权限给角色
     * @param roleId      角色ID
     * @param permission  权限名
     * @return
     */
    @Insert("insert into role_and_permission (roleid, permission) values(#{roleid}, #{permission})")
    public int addPermission(@Param("roleid") int roleId, @Param("permission") String permission);

}